<template>
	<view class="container">
		<!-- 提示窗示例 -->
		<uni-popup ref="fullCartDialog" type="dialog">
			<view class="uni-tip">
				<text class="uni-tip-title">提示</text>
				<view class="popup-content uni-tip-content">
					购物车装不下啦，请清理后再试！
				</view>
				<view class="uni-tip-group-button">
					<text class="uni-tip-button" @click="closeFullCartDialog()">取消</text>
					<navigator url="/pages/cart/cart" open-type="switchTab" class="uni-tip-button confirm">
					<text  >前往购物车</text>
					</navigator>
				</view>
			</view>
		</uni-popup>
		<image class="top-back" src="../../static/top-back.png" v-show="showToTop" @click="toTop()"></image>
	<view class="addTitle">
      <view class="titleDetail">
        <view class="titleLeft" >
			<image src="../../static/newh5/fanhui.png"
			class="yticon"
			style="width: 13px;height: 20px;color:black"
			@click="returnIndex()"
			></image>
        </view>
        <view class="titleCenter" >
          <b class="titleText">商品详情</b>
        </view>
        <view class="titleRight"  style="color: #269cd3;flex:1" > </view>
      </view>
    </view>
		<view class="carousel">
			<swiper indicator-dots circular=true duration="400">
				<swiper-item class="swiper-item" v-for="(item,index) in detailInfo.goods.goodsImageList" :key="index">
					<view class="image-wrapper">
						<image :src="item.url" class="loaded" mode="aspectFill"></image>
						<image v-if="isDisabled"  :class="['loaded','soldout']" src="../../static/outOfStock1.png" mode="aspectFill" lazy-load/>
					</view>
				</swiper-item>
			</swiper>
		</view>

		<view class="introduce-section">
			<text class="title more-t">{{detailInfo.goods.goodsName}}</text>
			<!-- <view class="goodsId">商品ID：{{detailInfo.goodsId}}</view> -->
			<!-- <view class="goodsId">商品所属采购目录：[{{detailInfo.protocol.purchaserCatalogName}}]</view> -->
			<view class="price-box ">
				<!-- <text class="price-tip">¥</text> -->
				<text class="tit " style="color: #303133">金额</text>
				<view class="price-show" v-if="hasLogin">
					<text class="price">¥{{detailInfo.protocol.goodsPrice}}</text>
				</view>
				<view v-else class="price-show">
					<text class="price" style="color: #fa436a;">******</text>
				</view>
				<text @click="showDiscountModal=true" style="color:#df3325;" v-if="goodsMarketing&&goodsMarketing.type">
					<template v-if="goodsMarketing.ruleList&&goodsMarketing.ruleList.length>0&&goodsMarketing.type==1">
						<text>{{goodsMarketing.ruleList[0].num}}件{{goodsMarketing.ruleList[0].discount}}折</text>
					</template>
					<u-icon name="arrow-down" style="transform: scaleX(.8);" />
				</text>
			</view>
		</view>

		<view class="c-list">
			<view class="c-row b-b" v-if="hasLogin">
				<text class="tit">官网价</text>
				<text class="m-price">¥{{detailInfo.protocol.marketPrice}}</text>
				<view class="draer-list-con flex " style="flex: 3;">

					<text>优惠率</text>
					<view style="padding: 10rpx 28rpx;">{{detailInfo.protocol.saveAmountRate}}</view>
				</view>



			</view>
			<view class="c-row b-b" v-if="detailInfo.goods.brandName!==''">
				<text class="tit">商品品牌</text>
				<text class="con t-r m-message">{{detailInfo.goods.brandName}}</text>
			</view>
			<view class="c-row b-b" v-if="detailInfo.goods.goodsCode!==''">
				<text class="tit">商品编码</text>
				<text class="con ">{{detailInfo.goods.goodsCode}}</text>
			</view>
			<view class="c-row b-b">
				    <text >
				      配送时效：<text >{{deliveryInfo}}</text>
				    </text>
				  </view>

				  <view class="c-row b-b" v-if="postageConf.distributionRuleIsEnabled">
				    <text >
				      运费：<text v-if="(Number(detailInfo.protocol.goodsPrice)) >= postageConf.postageThreshold">免运费</text><text v-else>{{ postageConf.postage }} (满{{ postageConf.postageThreshold }}元免运费)</text>
				    </text>
				  </view>
				  <view class="c-row b-b" v-else>
				  		  <text>运费：{{postageConf.postage==0?'免运费':postageConf.postage+'元'}}</text>
				  </view>
			      <view class="c-row b-b" v-if="(detailInfo.goods.moq != null) && (detailInfo.goods.moq > 0)">
			        <text>
			          起订量：<text style="color:#ccc;">{{detailInfo.goods.moq}}{{detailInfo.protocol.goodsUnit}}</text>
			        </text>
			      </view>
			<view class="c-row b-b" v-if="supplierInfoShow"  @click="showSupplier">
				<text class="tit">供应商</text>
				<text class="con t-r" style="flex: 1;"  @click.stop="jumpStore(detailInfo.protocol)">{{detailInfo.protocol.supplierName}}<text style="color: #300313;" class="yticon icon-you"></text></text>
				<u-image v-if="detailInfo.goods.protocolType === '03' && detailInfo.goods.productLogo"
					:src="detailInfo.goods.productLogo" width="128rpx" height="52rpx"></u-image>
				<text style="color: #909399;">联系供应商</text>
				<text class="yticon icon-you"></text>
			</view>
			<view class="c-row b-b" v-if="hasLogin&&detailInfo.goods.goodsCode!==''" @click="toshow('select')">
				<text class="tit">已选</text>
				<text class="con t-r m-message"><text v-if="detailInfo.skuList!=null">{{selectGood}}</text></text>
				<text class="yticon icon-you"></text>
			</view>
			<view class="c-row b-b" v-if="detailInfo.goods.areaName!==''" @click="toshow('select2')">
				<text class="tit">送至</text>
				<!-- <text class="con t-r m-message">{{detailInfo.goods.areaName}}</text> -->
				<text class="con t-r m-message"><text
						v-if="detailInfo.goods.areaName!==''">{{address}}</text></text>
				<text class="yticon icon-you"></text>
			</view>
			<view class="c-row b-b" v-if="detailInfo.goods.goodsCode!==''" @click="toshow('select3')">
				<text class="tit">参数</text>
				<text class="con t-r m-message" style="color: #909399"><text v-if="detailInfo.goods.specList!=null">规格参数</text></text>
				<text class="yticon icon-you"></text>
			</view>
		</view>

		<!-- 评价 -->
		<view class="eva-section" v-if="reviews.page.records.length>0">
			<view class="e-header" @click="toReviews()">
				<text class="tit">评价</text>
				<text>({{reviews.page.total}})</text>
				<text class="tip">好评率 {{Number(reviewRate.highRate * 100)}}%</text>
				<text class="yticon icon-you"></text>
			</view>
			<view class="eva-box" v-for="(item,index) in reviews.page.records.filter(i=>!i.parentId)" :key="index">
				<image class="portrait" src="http://img3.imgtn.bdimg.com/it/u=1150341365,1327279810&fm=26&gp=0.jpg"
					mode="aspectFill"></image>
				<view class="right">
					<text class="name">{{item.username}}</text>
					<view class="con">
						<uni-rate style="margin-bottom: 15rpx;" disabled :value="item.score" color="#bbb"
							disabledColor="#ffca3e" />
						<text>
							{{item.content}}
						</text>
					</view>
					<view v-if="item.files.length!=0" class="imageBox">
						<u-upload
						width="160"
						height="160"
						style="display:flex;flex-wrap: wrap;"
						:max-count='item.files.length-1'
						:file-list='turnImg( item.files)'
						:show-progress="false"
						:deletable='false'
						/>
					</view>
					<text class="time">{{item.createTime}}</text>
				</view>
			</view>
		</view>
		<view v-else class="eva-empty">
			<text>暂无评价</text>
		</view>

		<view class="detail-desc">
			<view class="d-header">
				<text>商品详情</text>
			</view>
			<view class="desc">
				<text class="name">商品名称：{{detailInfo.goods.goodsName}}</text>
				<view class="html" id="html" v-if="detailInfo.goods.goodsDesc" style="height: auto;">
					<view v-html="detailInfo.goods.goodsDesc" style="height: auto;"></view>
				</view>
				<view v-for="(img,index) in detailInfo.goods.descImages">
					<image :src="img" mode="aspectFit"></image>
				</view>
			</view>
		</view>

		<!-- 底部操作菜单 -->
		<view class="page-bottom">
			<navigator url="/pages/index/index" open-type="switchTab" class="p-b-btn">
				<text class="yticon icon-xiatubiao--copy"></text>
				<text>首页</text>
			</navigator>
			<navigator url="/pages/cart/cart" open-type="switchTab" class="p-b-btn">
				<text class="yticon icon-gouwuche"></text>
				<text>购物车</text>
			</navigator>
			<view class="p-b-btn" :class="{active: favorite}" @click="toFavorite">
				<text class="yticon icon-shoucang"></text>
				<text>收藏</text>
			</view>

			<!-- <view class="action-btn-group"> -->
			<!-- <button type="primary" class=" action-btn no-border buy-now-btn" @click="buy">立即购买</button> -->
			<button type="primary" class="btn-area no-border add-cart-btn" :class="isDisabled?'disabled':'able'"
				@click="addCart()">{{hasLogin?'加入购物车':'登录查看'}}</button>
			<button v-if="isShowDoOrder" type="primary" :disabled="actionDisabled" class="btn-area-now no-border add-cart-btn"
							@click="buyNow">{{hasLogin?'立即下单':'登录查看'}}</button>
			<!-- </view> -->
		</view>

<u-popup v-model="open" mode="bottom" height="80%" border-radius="20" closeable>
			<view style="padding: 30rpx;">
				<view style="color: #333;font-size: 30rpx;text-align: center;font-weight: bold;">抱歉，当前商品已失效，为您推荐以下商品</view>
				<scroll-view class="keyword-box" scroll-y>
				<WaterfallsFlow @addCart='likeAddCart' :wfList='recommendList' @itemTap="navToFloorItemDetail"
					:hasLogin="hasLogin" :showBeforeLogin="isShowPriceUnlogin" />
					</scroll-view>
			</view>
		</u-popup>
		<z-multi-choose :actualRemainAmount="actualRemainAmount" :sampleApplication="sampleApplication" activeColor="red" :updateAddress='updateAddress' :areaId='areaId' :addnum='addchildnum' :res='res' :goodsData='goodsData' :skuItems='skuItems' :type='type'
			:selectedItem='selectedItem' :selectDatas='selectData' :children='children' idKey="uid" showKey="name"
			:list="detailInfo" :selectGood='selectGood' :show="control" @maskTouch="cancle" @sure="sure" @cancle="cancle" @loadData="loadDatas"
			@selectAddress='selectAddress' :isShowStock="isShowStock" :stockStatus="stockStatus" @changenum='changenum' @receviverMsg='receviverMsg' @getChildData="getChildData"></z-multi-choose>
		<online-service v-if="isShowCustomerService" is-platform></online-service>
		<u-popup v-model="supplierShow" mode="bottom" height="40%" border-radius="20" closeable>
			<view style="padding: 30rpx;">
				<view style="color: black;font-size: 34rpx;text-align: center;font-weight: bold;">供应商联系方式</view>
				<view style="display: flex;align-items: center;padding: 40rpx;">
					<text style="width: 30%;">{{supplierData.supplierContact}}</text>
					<text class="yticon" style="margin: 0 10rpx;text-decoration: none;" @click="makePhoneCall(supplierData.supplierContactPhone)">
					  <uni-icons type="phone" size="18"></uni-icons>
					</text>
					<text style="flex: 1;">{{supplierData.supplierContactPhone}}</text>
					<online-service v-if="supplierCustomerGroup.customerGroupId" @service="toOnlineService()"></online-service>
				</view>
			</view>
		</u-popup>
		<u-popup v-model="showDiscountModal" mode="bottom" height="30%" closeable>
			<discount :data="goodsMarketing"></discount>
		</u-popup>
	</view>

</template>

<script>
	import OnlineService from '../../components/online-service/online-service.vue'
	import Discount from '../../components/marketing/discount.vue'
import {  goback } from "@/common/utils/navigateBack.js";
	let spliter = "\u2299";
	import zMultiChoose from '@/components/z-multi-choose/z-multi-choose.vue';
	import share from '@/components/share';
	import uniRate from '../../components/uni-rate/uni-rate.vue'
	import {
		getGoodsDetailInfo,
		favorites,
		getReviewList,
		getReviewRate,
		addCollection,
		removeCollection,
		saveOrUpdateHistory,
		getDeliveryInfo,
		orderNow,
		getConfFreight,
		getActivityGoods
	} from '@/api/product/list.js'
	import { showRuleSupplierInfoShow, qryConfByItemCode, getCustomerGroupBySupplierId } from '@/api/user/user.js'
	import {
		addToCart
	} from '../../api/cart/cart.js'
	import {
	  setDefault,
	  updateAddr,
	  addAddr,
	  loadAddr,
	  loadChildAddr,
	  queryGoodsLowestPriceById,
	  qryGuessHotGoods
	} from '../../api/order/order.js'
		import {
			queryDefinedHotGoods
		} from '../../api/order/order';
		import WaterfallsFlow from '@/components/WaterfallsFlow/WaterfallsFlow'

	import { onlineService } from '../../api/index';
	import {
		jugdeShopSetting
	} from '../../api/hotStores/hotStores.js'
	import {
		mapState
	} from 'vuex';
		import {
			getConfByType
		} from '../../api/conf/conf.js';
		import
		lPopup
		from "@/components/l-popup/l-popup.vue";
	export default {
		components: {
			share,
			uniRate,
			zMultiChoose,
			WaterfallsFlow,
			OnlineService,
			lPopup,
			Discount
		},
		data() {
			return {
				// 展示多件折扣活动信息
				showDiscountModal: false,
				// 营销活动信息
				goodsMarketing: {
					data:{}
				},
				addnum:1,
						isShowDoOrder:true,
				actionDisabled: false,

				addchildnum:0,
				recommendList:[],
				address:'',
				control: false,
				children: [{
					num: 1
				}],
				type: '',
				selectGood: '',
				nowGood: '',
				list: [{
						name: '冉遗',
						uid: 1,
					},
					{
						name: '毕方',
						uid: 2
					}, {
						name: '鸾鸟',
						uid: 3
					}, {
						name: '玃如',
						uid: 4
					}, {
						name: '溪边',
						uid: 5
					}, {
						name: '文鳐',
						uid: 6
					}, {
						name: '白雉',
						uid: 7
					}, {
						name: '白泽',
						uid: 8
					}
				],
				previewVisible: false,
      			previewImage: "",
				specClass: 'none',
				showModel4: true,
				showModel3: false,
				// 是否屏蔽购物车按钮
				isDisabled: false,
				specSelected: [],
				detailInfo: {
					goods: {},
					protocol: {}
				},
				favoritesList: [],
				cartValue: 1,
				stockStatus: '有货',
				stock: 0,
				goodsId: '',
				reviews: {
					page: {
						records: []
					}
				},
				reviewRate: {},
				favorite: false,
				skuItems: [],
				res: {},
				selectData: [],
				selectedItem: [],
				areaId: '',
				areaName: "", //配送地址
				goodsData: {
					effective: {},
					goods: {},
					protocol: {},
					sameGoodsList: [],
					similarGoodsList: [],
					recommendGoodsList: [],
					hotSaleSimilarGoodsList: [],
					// 相近价格商品列表
					similarPriceGoodsList: [],
					similarPriceGoodsListAll: [],
					// 相似配置商品
					sameConfigGoodsList: [],
					sameConfigGoodsListAll: [],
					approximatePriceGoodsList: []
				},
				goodsUpc: "",
				//商品价格
				goodsPrice: 0,
				isTokenShow: false,
				isShowPriceUnlogin: '0',
				//商品价格-字符串
				goodsPriceStr: 0,
				// selectedItem: [],
				province:[],
				city:[],
				updateAddress:false,
				//是否显示库存 0否 1是
				      isShowStock:true,
				// 供应商隐藏
				supplierInfoShow: true,
				// 广州银行-校验商品最低价
				isbuyMinPrice:false,
				 // 邮费配置
						      postageConf: {
						        postageThreshold: 0,
						        postage: 0,
						        distributionRuleIsEnabled: false,
						        distributionRuleController: '0',
						      },
				// 华润-是否开启打样单
				sampleApplication: false,
				showToTop: false,
								listScrollTop:0,
										deliveryInfo:"",
										open:false,
														goodsSupplierShowConfigForm:{
														  "goodsShowRule_supplierInfoShow":"",
										          showGoodsURL: ''
														},

				// 是否显示平台客服
				isShowCustomerService:0,
				supplierShow:false,
				supplierData:{},
				supplierCustomerGroup:{},
				isShowStockUnlogin: false,
				      actualRemainAmount: false,
					  isShowStock:false

			};
		},
		onShow() {
			//界面隐藏拉取
			this.updateAddress = false
		},

		onLoad(options) {
			// 初始化是否显示客服
			this.isShowCustomerService = uni.getStorageSync('isShowCustomerService')
			  ? Number(uni.getStorageSync('isShowCustomerService')) : 1
			//初始化页面
			if(getApp().globalData.needRefresh){
				getApp().globalData.needRefresh = 0
				location.reload()
				return
			}
						this.loadOtherConfig();

			this.goodsId = options.id
			this.loadData()
			// 加载营销活动
			this.loadMarketing()
			this.loadSupplierInfoShow()
			// this.initLoadArea()
			if (this.hasLogin) {
				this.getFavorites()
				this.getReviews()
				this.getConf()
				this.getSampleConf()
				this.isShowStockUnlogin = true
			}else {
				let setting = uni.getStorageSync("portalSettingsInfo")
				console.log(setting)
				if(setting.unLoginShowModule&&setting.unLoginShowModule.indexOf('0') > -1){
				          this.isShowStockUnlogin = true;
				        };
			}
			this.getQueryDefinedHotGoods()
			console.log('2131',this.detailInfo);
		},
		computed: {
			...mapState(['hasLogin'])
		},
		onPageScroll(e) {
					//兼容iOS端下拉时顶部漂移
					this.listScrollTop = e.scrollTop
					this.showToTop = this.listScrollTop > 0 ? true : false
				},
		methods: {
			// 加载营销活动
			loadMarketing() {
				getActivityGoods(this.goodsId).then(res => {
					if (res.code === 0) {
						this.goodsMarketing = res.data || {}
					}
				})
			},
			jumpStore(item) {
					console.log(item)
					jugdeShopSetting({
						code: item.supplierId
					}).then(res => {
						if (res.code == 0) {
							if (JSON.stringify(res.data) != '{}') {
								uni.navigateTo({
									url: `/pages/hotList/hotStore?id=${res.data.supplierId}`
								})
							} else {
                uni.navigateTo({
                  url: `/pages/product/list?key=${item.supplierName}`+`&supplierId=${item.supplierId}`
                })
							}
						}
					})
			},
			makePhoneCall(phone){
				uni.makePhoneCall({
					phoneNumber: phone
				});
			},
			getSupplierCustomerGroup(id){
				getCustomerGroupBySupplierId({'supplierId':id}).then(res=>{
					if(res.code===0){
						this.supplierCustomerGroup = res.data
					}
				})
			},
			toOnlineService(){
				const content = `商品名称:${this.detailInfo.goods.goodsName}\n商品编码:${this.detailInfo.goods.goodsCode}`
				onlineService({ "type": "goods", "content": content,"vendorId": this.supplierCustomerGroup.customerGroupId}).then(res=>{
					if(res.code === 0){
						window.location.href=res.data
					}
				})
			},
			showSupplier(){
				this.supplierShow = !this.supplierShow
			},
				buyNow() {
							if (!this.hasLogin) {
								this.$util.msg('您还未登录，请登录')
								setTimeout(() => {
									uni.navigateTo({
										url: '/pages/public/login'
									})
								}, 500)
							} else {
								//防止直接购买时无收货地址
								if (!uni.getStorageSync('areaId')) {
									uni.showModal({
										title: '提示',
										content: '当前账号无收货地址，请前往添加收货地址',
										confirmText: '立即前往',
										cancelText: '稍后添加',
										success: (suc) => {
											if (suc.confirm) {
												uni.navigateTo({
													url: '/pages/address/address'
												})
											}
										}
									})
									return
								}
								//存在购买数量限制，起码要校验单次购买得数量不能超过限购数量
								if (this.userLimitNum) {
									if (this.addnum > this.userLimitNum) {
										uni.showToast({
																			title: '购买数量已超过该团购商品的限购数量,无法下单',
																			icon: 'error',
																		});
										// this.$util.msg('购买数量已超过该团购商品的限购数量,无法下单')
										return
									}
								}
			          // 检查起订量
			          if ((this.detailInfo.goods.moq != null) && (this.detailInfo.goods.moq > this.addnum)) {
			            // this.$util.msg('未达到起订量！')
						uni.showToast({
															title: '未达到起订量',
															icon: 'error',
														});
			            return
			          }
								uni.showLoading({
									mask: true,
									title: '创建订单中'
								})
								const params = {
									areaId: this.detailInfo.goods.areaId,
									goodsId: this.detailInfo.goods.goodsId,
									num: this.addnum
								}
								orderNow(params).then(res => {
									uni.hideLoading()
									if (res.code == 0) {
										uni.navigateTo({
											url: `/pages/order/createOrder?id=${this.groupBuyId}`
										})
									} else {
										uni.showToast({
																			title: res.message,
																			icon: 'error',
																		});
										// this.$util.msg(res.message)
									}
								}).catch(err => {
									console.log('下单失败', err)
									uni.hideLoading()
								})
							}
						},
			getQueryDefinedHotGoods() {
				if(this.hasLogin){
					qryGuessHotGoods({current:1,end:10}).then(res=>{
						if(res.code===0){
							if(res.data&&res.data.length>0){
								res.data.forEach(item=>{
									if(item.goodsImageList&&item.goodsImageList.length>0){
										item.goodsImage = item.goodsImageList[0].url
									}
								})
								this.recommendList = res.data
							}
						}
					})
				}else{
					queryDefinedHotGoods({
						specialAreaId:2,
						goodsNum:10
					}).then(res => {
						if(res.code == 0) {
							this.recommendList = res.data
						}
					})
				}
						},
						likeAddCart(item) {
							if (!this.hasLogin) {
								uni.showModal({
									title: '提示',
									content: '您还未登录，不能进行此操作',
									confirmText: '去登录',
									cancelText: '取消',
									success: (suc) => {
										if (suc.confirm) {
											uni.navigateTo({
												url: '/pages/public/login'
											})
										}
									}
								})
							} else {
								let pType;
								let qType;
								if (item.goodsSourceType === 0) {
									pType = '02';
									qType = 1;
								} else {
									pType = '01';
									qType = 2;
								}
								const good = {
									protocolGoodsId: item.goodsId,
									protocolId: item.protocolId,
									protocolType: pType,
									remainAmount: 1
								}
								/* const params = {
									areaId: uni.getStorageSync('areaId'),
									bizDeptId: uni.getStorageSync('bizDeptInfo').deptId,
									goods: [good],
									isqueryAmount: true,
									queryType: qType
								} */
								const params = {
									areaId: uni.getStorageSync('areaId'),
									goodsId: item.goodsId,
									num: 1
								}
								let userAreaId = uni.getStorageSync('areaId')
								if (userAreaId) {
									params['areaId'] = userAreaId
								} else {
									params['areaId'] = uni.getStorageSync('tenantAreaId')
								}
								addToCart(params).then(res => {
									if (res.code === 0) {
										 uni.showToast({
												title: '加入购物车成功',
												icon: 'success',
											});

									} else if(res.code === 1001) {
						this.$util.msg(res.message+res.productAvailability.message)
					}else {
										uni.showToast({
																			title: res.message,
																			icon: 'error',
																		});
										// this.$util.msg(res.message)
									}
								})
							}
						},
			    loadOtherConfig() {
			        const data = {
			          codes: ['goodsShowRule_supplierInfoShow', 'showGoodsURL',"isShowDoOrder","actualRemainAmount","isShowStock"]
			        }
			        getConfByType(data).then(response => {
			          if (response.code == 0) {
			            const list = response.data
			            list.forEach(item => {
			              if (item.code === 'goodsShowRule_supplierInfoShow') {
			                this.goodsSupplierShowConfigForm.goodsShowRule_supplierInfoShow = item.val
			              }
			              if (item.code === 'showGoodsURL') {
			                this.goodsSupplierShowConfigForm[item.code] = item.val
			              }
						  if(item.code === 'isShowDoOrder') {
						                   this.isShowDoOrder = item.val === '1'
						                }
										 if(item.code === 'actualRemainAmount') {
										                 this.actualRemainAmount = item.val === '1'
										              }
													   if(item.code==='isShowStock'){
													                  this.isShowStock = item.val === '1';
													                }
			            })
			          }
			        })
			      },
			handleCancel() {
							this.open = false
						},
						handleConfirm() {
									},
			  // 查询邮费
						    loadPostage() {
						      let postageParam = {
								 areaId: uni.getStorageSync('areaId')||this.areaId
							  }
							  postageParam.supplierCode = this.detailInfo.protocol.supplierId
							  postageParam.goodsId = this.detailInfo.goods.goodsId
							  postageParam.supplierName = this.detailInfo.protocol.supplierName
							  postageParam.isEplus = this.detailInfo.goods.protocolType == '03'
							  postageParam.protocolId = this.detailInfo.protocol.protocolId
							  getConfFreight(postageParam).then(res => {
								  if (res.code !== 0) {
								    return
								  }
								            this.postageConf.distributionRuleIsEnabled = res.data.distributionRuleIsEnabled;

								  // 邮费
								  this.postageConf.postage = Number(res.data.postage);
								  // 免邮阈值
								  this.postageConf.postageThreshold = Number(res.data.postageThreshold);
								  console.log(this.postageConf)
							  })
						    },
			 // 查询到货时间 version2
				        loadDeliveryInfo(param) {
							getDeliveryInfo(param).then(res => {
								if(res.code == 0) {
									this.deliveryInfo = res.data.content;
								}
							})

				        },
			toTop() {
							this.listScrollTop = 0;
							this.showToTop = false
							uni.pageScrollTo({
												scrollTop: this.listScrollTop,
												duration: 300
											});

						},
			getConf(){
				const deptInfo = uni.getStorageSync('deptinfo')[0]
				qryConfByItemCode({code: "isbuyMinPrice",
					tenant_id: deptInfo.tenantId,
					dept_code: deptInfo.deptCode}).then(res=>{
						if(res.code===0){
							this.isbuyMinPrice = res.data.val == '1'
						}
				})
			},
			getSampleConf(){
				const deptInfo = uni.getStorageSync('deptinfo')[0]
				qryConfByItemCode({code: "sample_application",
					tenant_id: deptInfo.tenantId,
					dept_code: deptInfo.deptCode}).then(res=>{
						if(res.code===0){
							this.sampleApplication = res.data.val == '1'
						}
				})
			},
			  // 获取是否屏蔽供应商信息配置
			  async loadSupplierInfoShow() {
				await showRuleSupplierInfoShow().then(res => {
				  if (res.code === 0) {
					this.supplierInfoShow = !res.data;
				  }
				})
			  },
			returnIndex() {
				goback()
			},
			turnImg(val){
				console.log('图片转换------',val);
				// if(val.length==0){

				// }
				let ii = []
				val.forEach(item=>{
					let urlC= {}
					urlC.url = item.fileUrl
					ii.push(urlC)
				})
				return ii
			},
			//回显图片方法
			 async handlePreview(file) {
				if (!file.url && !file.preview) {
					file.preview = await getBase64(file.originFileObj);
				}
				this.previewImage = file.url || file.preview;
				this.previewVisible = true;
			},
			// 适配地址的修改
			refreshList(){
				console.log('地址修改了！');
				this.updateAddress = true
			},
			//浏览历史记录添加
			saveOrUpdateHistory(){
				const params = {
					goodsPrice:this.detailInfo.protocol.goodsPrice,
					purchaserCatalogId:this.detailInfo.protocol.purchaserCatalogId,
					goodsName:this.detailInfo.goods.goodsName,
					goodsImageList:this.detailInfo.goods.goodsImageList,
					goodsId:this.detailInfo.goods.goodsId,
					//
					goodsTip:"",
					goodsImage:"",
					supplierId: this.detailInfo.protocol.supplierId,
					supplierName:this.detailInfo.protocol.supplierName,
					//
					goodsSource:this.detailInfo.protocol.goodsSourceType,
					purchaserCatalogName:this.detailInfo.protocol.purchaserCatalogName,
					brandName:this.detailInfo.goods.brandName
				}
				console.log('params',params);
				saveOrUpdateHistory(params).then(res=>{
					if(res.code == 0){
						console.log('res',res.data);
					}
				})
			},
			// 加载收货地区列表
			initLoadArea() {
			  loadAddr().then(res => {
				  console.log('diqu===================',res)
			    if (res.code === 0) {
			      this.province = res.data;
			      this.loadCity(this.province[0].id)
			    } else {
			      this.toast(res.message)
			    }
			  })
			},
			loadCity(parentId) {
			  const params = {
			    parentId: parentId
			  }
			  loadChildAddr(params).then(res => {
			    if (res.code === 0) {
			      this.city = res.data;
			      if (this.province[this.valueArr[0]].children === undefined) {
			        this.$set(this.province[this.valueArr[0]], 'children', [])
			        res.data.forEach(item => {
			          this.province[this.valueArr[0]].children.push(item)
			        })
			        this.loadArea(this.province[this.valueArr[0]].children[this.valueArr[1]].id,1)
			        //this.loadArea(this.province[this.valueArr[0]].children[this.valueArr[1]].children[this.valueArr[2]].id,2)
			      }
			    } else {
			      this.toast(res.message)
			    }
			  })
			},
			loadArea(parentId,level) {
			  const params = {
			    parentId: parentId
			  }
			  loadChildAddr(params).then(res => {
			    if (res.code === 0) {
			      this.area = res.data;
			      if(level===1)
			      {
			        if (this.province[this.valueArr[0]].children[this.valueArr[1]].children === undefined) {
			          this.$set(this.province[this.valueArr[0]].children[this.valueArr[1]], 'children', [])
			          res.data.forEach(item => {
			            this.province[this.valueArr[0]].children[this.valueArr[1]].children.push(item)
			          })
			        }
			        this.loadArea(this.province[this.valueArr[0]].children[this.valueArr[1]].children[this.valueArr[2]].id,2);
			      }
			      else if(level===2)
			      {
			        if (this.province[this.valueArr[0]].children[this.valueArr[1]].children[this.valueArr[2]].children === undefined) {
			          this.$set(this.province[this.valueArr[0]].children[this.valueArr[1]].children[this.valueArr[2]], 'children', [])
			          res.data.forEach(item => {
			            this.province[this.valueArr[0]].children[this.valueArr[1]].children[this.valueArr[2]].children.push(item)
			          })
			        }
			      }
			    } else {
			      this.toast(res.message)
			    }
			  })
			},
			getChildData(e) {
				console.log('子组件的值', e)
			},
			cancle() {
				this.control = false
			},
			sure(e) {
				console.log(e)
				this.control = false
			},
			// 弹出框事件
			toshow(value) {

				switch (value) {
					case 'select':
						// this.selectData = []
						this.type = '1';
						console.log('this.skuItems', this.skuItems)
						// for (let i = 0; i < this.detailInfo.skuList.length; i++) {
						// 	this.selectData.push({
						// 		title: this.detailInfo.skuList[i].specName,
						// 		data: {}
						// 	})
						// 	console.log('this.selectData', this.detailInfo.skuList[i].specValueList.length)

						// 	console.log('this.data', this.selectData[i].data)
						// 	this.selectData[i].data.list = []
						// 	this.selectData[i].data.type = 'radio'
						// 	console.log('第二次循环this.data', this.selectData[i].data)
						// 	console.log('第二次循环this.data', this.selectData[i].data.list)
						// 	if (this.detailInfo.skuList[i].specValueList.length !== 0) {
						// 		for (var j = 0; j < this.detailInfo.skuList[i].specValueList.length; j++) {
						// 			this.selectData[i].data.list.push({
						// 				text: this.detailInfo.skuList[i].specValueList[j].valueName,
						// 				id: this.detailInfo.skuList[i].specValueList[j].valueName
						// 			})
						// 		}
						// 	}

						// }
						this.selectData = this.detailInfo.skuList
						for (var i = 0; i < this.selectData.length; i++) {
							this.selectData[i].type = 'radio'
						}
						this.selectGood=this.nowGood
						console.log('selcetData', this.selectData);
						this.control = true;
						break;
					case 'select2':
						this.type = '3';
						this.control = true;
						break;
					case 'select3':
						this.type = '2';
						this.control = true;

						break;
				}
			},
			async loadDatas(id) {
				console.log('再次初始化方法=======================================')
				//uni.getStorageSync('deptinfo')[0].deptId
				let params = {
					goodsId: id,
					purchaserId: uni.getStorageSync('deptinfo')[0].deptId
				}
				await getGoodsDetailInfo(params).then(res => {
					this.detailInfo = res
					if(uni.getStorageSync('areaId')||this.areaId)
						this.loadPostage()

					console.log('details', this.detailInfo)
					if (this.detailInfo && this.detailInfo.goods && Object.keys(this.detailInfo.goods).length >
						0) {
						this.detailInfo.goodsId = this.goodsId
						// 判断商品状态
						this.checkGoodsStatus(this.detailInfo)
						// 创建商品数据
						this.createGoodsData(this.detailInfo)
						this.checkGoodStatus()
					} else {
						uni.showToast({
							title:'该商品已不存在！',
							icon: 'error',
						});
						// this.$util.msg('该商品已不存在！')
					}
				})

				/* this.detailInfo.skuList.forEach(item => {
					item.specValueList.sort((a, b) => {
						return a.valueName.length - b.valueName.length;
					})
				}) */
				// 设置商品sku属性
				this.setGoodsSku();
				this.stock = parseInt(this.detailInfo.protocol.remainAmount)

				if (this.stock === -999) {
					// this.stockStatus = '有货'
					this.stockStatus = this.detailInfo.protocol.actualRemainAmount
				} else if (this.stock <= 0) {
					this.stockStatus = '库存不足'
				} else {
					this.stockStatus = this.stock
				}
				console.log('this.detailInfo.effective', this.detailInfo.effective)
				//获取已选列表
				for (var i = 0; i < this.detailInfo.effective.length; i++) {
					// console.log('this.detailInfo.effective[i]', this.detailInfo.effective[i])
					if (this.detailInfo.goods.goodsId == this.detailInfo.effective[i]) {

					}
				}
				this.combineAttrs()
				//detailInfo.skuList[0].specName
				// console.log('this.skuItems', this.skuItems)
				// console.log('this.skuItems', this.skuItems)
				// 生成所有子集是否可选、库存状态 map
				this.buildResult(this.skuItems)
				// this.updateStatus()
				// console.log('detailInfo.skuList', this.detailInfo.skuList)
				//生成 已选内容
				this.selectData = this.detailInfo.skuList
				for (var i = 0; i < this.selectData.length; i++) {
					this.selectData[i].type = 'radio'
				}
				//配送至
				this.adderss=this.detailInfo.goods.areaName

				// 清空购物数量
				this.addnum=1
			},
			// 刷新页面
			async loadData() {
				let params = {
					goodsId: this.goodsId,
					purchaserId: uni.getStorageSync('deptinfo')[0].deptId
				}

				await getGoodsDetailInfo(params).then(res => {
					this.detailInfo = res
					if(this.detailInfo.goods.areaId) this.areaId = this.detailInfo.goods.areaId
					if (JSON.stringify(this.detailInfo) == '{}') {
										uni.showToast({
											mask: true,
											duration: 1500,
											title: '当前商品已失效',
											icon: 'none'
										})
										this.open = true;
										// setTimeout(() => uni.navigateBack(), 1500)
									}

									if ( uni.getStorageSync('areaId') != ""||this.areaId) {
									                  let dparams = {
									                    areaId: uni.getStorageSync('areaId')||this.areaId,
									                    protocolGoodsId: this.detailInfo.goods.goodsId,
									                    num: this.addnum,
									                  }
									                  this.loadDeliveryInfo({
									                    ...dparams,
									                    // purchaserId: appConfig.deptInfo[0].deptId,
									                    originGoodsId: this.detailInfo.goods.originGoodsId,
									                    protocolId: this.detailInfo.goods.protocolId,
									                    supplierId: this.detailInfo.protocol.supplierId,
                                                        protocolType: this.detailInfo.goods.protocolType
                                                      });

													  this.loadPostage()
									                }
					console.log('获得的商品数据_____+++++++',res);
					console.log('details', this.detailInfo)
					this.supplierData = res.protocol
					this.getSupplierCustomerGroup(this.supplierData.supplierId)
					if(this.hasLogin){
						this.saveOrUpdateHistory()
					}
					if (this.detailInfo && this.detailInfo.goods && Object.keys(this.detailInfo.goods).length >
						0) {
						this.detailInfo.goodsId = this.goodsId
						// 判断商品状态
						this.checkGoodsStatus(this.detailInfo)
						// 创建商品数据
						this.createGoodsData(this.detailInfo)

						this.checkGoodStatus()
					} else {
						uni.showToast({
							title:'该商品已不存在！',
							icon: 'error',
						});
						// this.$util.msg('该商品已不存在！')
					}
				})

				/* this.detailInfo.skuList.forEach(item => {
					item.specValueList.sort((a, b) => {
						return a.valueName.length - b.valueName.length;
					})
				}) */
				// 设置商品sku属性
				this.setGoodsSku();
				this.stock = parseInt(this.detailInfo.protocol.remainAmount)
				if (this.stock === -999) {
					this.stockStatus = this.detailInfo.protocol.remainAmount
				} else if (this.stock <= 0) {
					this.stockStatus = '库存不足'
										this.actionDisabled = true;

				} else {
					this.stockStatus = this.stock
				}
				console.log('this.detailInfo.effective', this.detailInfo.effective)
				//获取已选列表
				for (var i = 0; i < this.detailInfo.effective.length; i++) {
					console.log('this.detailInfo.effective[i]', this.detailInfo.effective[i])
					if (this.detailInfo.goods.goodsId == this.detailInfo.effective[i]) {

					}
				}
				this.combineAttrs()
				//detailInfo.skuList[0].specName
				// console.log('this.skuItems', this.skuItems)
				// console.log('this.skuItems', this.skuItems)
				// 生成所有子集是否可选、库存状态 map
				this.buildResult(this.skuItems)
				this.updateStatus()
				console.log('detailInfo.skuList', this.detailInfo.skuList)
				//配送至
				this.address=this.detailInfo.goods.areaName
				console.log('add',this.address)

			},
			checkGoodStatus() {
							if (this.detailInfo.goods.saleStatus === 0 || this.detailInfo.protocol.protocolStatus !== '02') {
								this.actionDisabled = true;

								// this.$util.msg('该商品已下架，无法进行购买')
								uni.showToast({
																	title: '该商品已下架，无法进行购买',
																	icon: 'error',
																});
																this.open = true
							} else {
								// if (!this.detailInfo.goods.purchaserVisible) {
								// 	this.actionDisabled = true;
								// 	uni.showToast({
								// 										title: '该商品已失效，无法进行购买',
								// 										icon: 'error',
								// 									});
								// 	// this.$util.msg('该商品已失效，无法进行购买')
								// }
							}
						},
			// 设置商品sku属性
			setGoodsSku() {
				this.selectedItem = []
				for (let i = 0; i < this.detailInfo.skuList.length; i++) {
					let specValueList = this.detailInfo.skuList[i].specValueList;
					for (let j = 0; j < specValueList.length; j++) {
						this.$set(specValueList[j], "isflag", false);
						this.$set(specValueList[j], "isdisabled", false);
					}
				}
				for (let i = 0; i < this.detailInfo.skuList.length; i++) {
					let spValList = this.detailInfo.skuList[i];
					let checkId = spValList.specName;
					for (var k = 0; k < this.detailInfo.goods.specList.length; k++) {
						let getFlag = this.detailInfo.goods.specList[k];
						let specKeyList = Object.keys(getFlag);
						if (specKeyList.length == 0) continue;
						let id = getFlag.specName;
						let valueId = getFlag.specValueList[0].valueName;
						if (id == checkId) {
							for (var n = 0; n < spValList.specValueList.length; n++) {
								if (spValList.specValueList[n].valueName == valueId) {
									this.selectedItem.push(spValList.specValueList[n].valueName);
									spValList.specValueList[n].isflag = true;
									break;
								}
							}
							break;
						}
					}
				}
			},
			// 创建商品数据
			createGoodsData(data) {
				this.selectedItem=[]
				let goodsId = data.goodsId;
				if (data.goods.areaId && data.goods.areaName) {
					this.areaId = data.goods.areaId;
					this.areaName = data.goods.areaName;
				}
				//this.isShowPriceUnlogin = data.goods.isShowPriceUnlogin;
				this.goodsData.effective = data.effective;
				this.goodsData.goods = data.goods;
				this.goodsUpc = data.goods.upc;
				this.goodsPrice = data.protocol.goodsPrice;
				if (this.isTokenShow || this.isShowPriceUnlogin == '1') {
					this.goodsPriceStr = filterMoney(this.goodsPrice);
				} else {
					this.goodsPrice = "******";
					this.goodsPriceStr = "******";
				}
				// 为了解决加入对比没有价格的问题
				data.goods.goodsPrice = this.goodsPrice;
				this.goodsData.skuList = data.skuList;
				if (this.goodsData.skuList) {
					for (var i = 0; i < this.goodsData.skuList.length; i++) {
						var specValueList = this.goodsData.skuList[i].specValueList;
						for (var j = 0; j < specValueList.length; j++) {
							this.$set(specValueList[j], "isflag", false);
							this.$set(specValueList[j], "isdisabled", false);
						}
					}
					for (let i = 0; i < this.goodsData.skuList.length; i++) {
						let spValList = this.goodsData.skuList[i];
						let checkId = spValList.specName;
						for (var k = 0; k < this.goodsData.goods.specList.length; k++) {
							let getFlag = this.goodsData.goods.specList[k];
							let specKeyList = Object.keys(getFlag);
							if (specKeyList.length == 0) continue;
							let id = getFlag.specName;
							let valueId = getFlag.specValueList[0].valueName;
							if (id == checkId) {
								for (var n = 0; n < spValList.specValueList.length; n++) {
									if (spValList.specValueList[n].valueName == valueId) {
										this.selectedItem.push(spValList.specValueList[n].valueName);
										console.log('初始化', this.selectedItem)
										spValList.specValueList[n].isflag = true;
										break;
									}
								}
								break;
							}
							break;
						}
					}
					if (
						this.goodsData.skuList.length > 0 &&
						this.goodsData.skuList[0].specValueList.length == 0
					) {
						this.goodsData.skuList = [];
					}
				} else {
					this.goodsData.skuList = [];
				}
				this.$nextTick(function(){
					this.jdStyleFunc()
				})
			},
			jdStyleFunc(){
				const goodsDesc = this.goodsData.goods.goodsDesc
				if(goodsDesc&&goodsDesc.length>0&&goodsDesc.indexOf('ssd-module')!==-1){
					const ssdModules = document.getElementsByClassName('ssd-module-wrap')[0].children
					for(let i =0;i<ssdModules.length;i++){
						const ele = ssdModules[i]
						ele.style.height = ele.offsetHeight/(750/window.innerWidth)+'px'
					}
				}
			},
			// 判断商品状态
			checkGoodsStatus(data) {
				// console.log('判断商品状态',data);
				// 商品状态 1是商品可用，2是商品下架，3是商品失效
				let goodsStatus = data.goods.goodsStatus
				let remainAmount = data.protocol.remainAmount
				// 赋值库存
				this.getRemain(data, remainAmount, data.protocol.stockStateDesc)
				if (goodsStatus == "2") {
					this.isDisabled = true
					this.$util.msg('该商品已下架，无法进行购买')
					return;
				}
				if (goodsStatus == "3") {
					this.isDisabled = true
					this.$util.msg('该商品已失效，无法进行购买')
					return;
				}
			},
			// 赋值库存
			getRemain(data, remainAmount, stockStateDesc) {
				if (remainAmount == -999) {
					this.isDisabled = false;
					this.stockStatus = data.protocol.actualRemainAmount;
				} else if (remainAmount <= 0) {
					this.isDisabled = true;
					this.stockStatus = '库存不足';
				} else if (remainAmount > 0 && remainAmount < 50) {
					this.isDisabled = false;
					this.stockStatus = remainAmount;
				} else {
					this.isDisabled = false;
					this.stockStatus = stockStateDesc;
				}
			},

			combineAttrs() {
				this.skuItems=[]
				let min = this.detailInfo.protocol.goodsPrice;
				let max = this.detailInfo.protocol.goodsPrice;
				let effective = this.detailInfo.effective;
				let tempArr = [];
				let goodsPrice = 0;
				if (effective) {
					Object.keys(effective).forEach(key => {
						tempArr = [];
						let arrs = effective[key].specList;
						goodsPrice = effective[key].goodsPrice;
						for (let index in arrs) {
							if (
								arrs[index].specValueList &&
								arrs[index].specValueList.length > 0
							) {
								tempArr.push(arrs[index].specValueList[0].valueName);
							}
						}
						this.skuItems.push({
							path: tempArr.join(spliter),
							goodsId: key,
							goodsPrice: goodsPrice
						});
						if (min > goodsPrice) {
							min = goodsPrice;
						}
						if (max < goodsPrice) {
							max = goodsPrice;
						}
						if (key === this.goodsId) {
							this.detailInfo.skuList.forEach(item => {
								item.specValueList.forEach((spec, i) => {
									tempArr.forEach(arr => {
										if (spec.valueName === arr) {
											this.$set(item, 'selectedIndex', i)
										}
									})
								})
							})
						}
					});
				}
			},

			/* 生成所有子集是否可选、库存状态 map */
			buildResult(items) {
				let allKeys = this.getAllKeys(items);
				for (let i = 0; i < allKeys.length; i++) {
					let curr = allKeys[i];
					let goodsId = items[i].goodsId;
					let values = curr.split(spliter);

					let allSets = this.powerset(values);

					// 每个组合的子集
					for (let j = 0; j < allSets.length; j++) {
						let set = allSets[j];
						let key = set.join(spliter);
						if (this.res[key]) {
							this.res[key].goodsIds.push(goodsId);
						} else {
							this.res[key] = {
								goodsIds: [goodsId]
							};
						}
					}
					for (let i = 0; i < items.length; i++) {
						if (items[i].goodsId === this.detailInfo.goods.goodsId) {
							this.selectGood = items[i].path
							// console.log('this.selectGood', this.selectGood)
							this.selectGood = this.selectGood.replace(/[\u2299]/g, ',');
						}
					}
					this.nowGood=this.selectGood
					console.log('this.selectGood', this.selectGood)
				}
			},
			getAllKeys(arr) {
				let result = [];
				for (let i = 0; i < arr.length; i++) {
					result.push(arr[i].path);
				}
				return result;
			},
			powerset(arr) {
				let ps = [
					[]
				];
				for (let i = 0; i < arr.length; i++) {
					for (let j = 0, len = ps.length; j < len; j++) {
						ps.push(ps[j].concat(arr[i]));
					}
				}
				return ps;
			},
			trimSpliter(str, spliter) {
				let reLeft = new RegExp("^" + spliter + "+", "g");
				let reRight = new RegExp(spliter + "+$", "g");
				let reSpliter = new RegExp(spliter + "+", "g");
				return str
					.replace(reLeft, "")
					.replace(reRight, "")
					.replace(reSpliter, spliter);
			},
			updateStatus() {
				let selected = this.selectedItem;
				let keys = this.detailInfo.skuList;
				for (let i = 0; i < keys.length; i++) {
					let key = keys[i];
					let data = key.specValueList;
					let copy = selected.slice();
					for (let j = 0; j < data.length; j++) {
						let itemObj = data[j];
						let item = itemObj.valueName;
						if (selected[i] == item) continue;
						copy[i] = item;
						let curr = this.trimSpliter(copy.join(spliter), spliter);
						if (this.res[curr]) {
							itemObj.isdisabled = false;
						}
						// else {
						// 	itemObj.isdisabled = true;
						// }
					}
				}
				console.log(this.detailInfo.skuList);
			},
			//选择规格
			selectSpec(childItem, index, childIndex) {
				if (childItem.isdisabled || childItem.isflag) {
					return;
				}
				this.$set(this.detailInfo.skuList[index], 'selectedIndex', childIndex)
				let list = this.detailInfo.skuList;
				let arr = []
				list.forEach(item => {
					arr.push(item.specValueList[item.selectedIndex].valueName)
				})
				this.skuItems.forEach(sku => {
					if (sku.path === arr.join(spliter))
						uni.redirectTo({
							url: `/pages/product/product?id=${sku.goodsId}`
						})
				})
			},
			// //选择规格
			// selectSpec(childItem, index, childIndex) {
			// 	this.$set(this.detailInfo.skuList[index], 'selectedIndex', childIndex)
			// 	this.skuItems.forEach(sku => {
			// 		sku.path.forEach(p => {
			// 			if (p === childItem.valueName) {
			// 				this.goodsId = sku.goodsId
			// 				this.loadData()
			// 				this.getFavorites()
			// 				this.getReviews()
			// 			}
			// 		})
			// 	})
			// },
			getReviews() {
				const params = {
					pid: this.goodsId,
					page: 1,
					limit: 2
				}
				getReviewList(params).then(res => {
					if (res.code === 0)
						this.reviews = res.data
				})
				getReviewRate(params).then(res => {
					if (res.code === 0) {
						this.reviewRate = res.data
					}
				})
			},
			getFavorites() {
				favorites().then(res => {
					if (res.code === 0) {
						this.favoritesList = res.data;
						this.favoritesFilter()
					}
				})
			},
			favoritesFilter() {
				this.favorite = this.favoritesList.includes(this.goodsId) ? true : false;
			},
			editNum(type) {
				var num = parseInt(this.addnum);
				this.addnum = type === 0 ? (num <= 1 ? this.addnum : num - 1) : (num + 1);
			},
			editInputNum(e) {
				var exceptNum = e.detail.value;
				if (!/^\d*[1-9]\d*$/.test(exceptNum)) {
					this.$util.msg('请填写整数！')
					return;
				}
				this.addnum = parseInt(exceptNum);
			},
			//收藏
			toFavorite() {
				if (!this.hasLogin) {
					this.$util.msg('您还未登录，无法操作')
					return;
				}
				if (this.favorite) {
					const param = {
						product_id: this.goodsId
					}
					removeCollection(param).then(res => {
						if (res.code === 0) {
							this.favorite = !this.favorite
							if (this.favorite) {
								this.$util.msg('收藏成功')
							} else {
								this.$util.msg('取消收藏成功')
							}
						} else {
							this.$util.msg(res.message)
						}
					})
				} else {
					const param = {
						productId: this.goodsId
					}
					addCollection(param).then(res => {
						if (res.code === 0) {
							this.favorite = !this.favorite;
							if (this.favorite) {
								this.$util.msg('收藏成功')
							} else {
								this.$util.msg('取消收藏成功')
							}
						} else {
							this.$util.msg(res.message)
						}
					})
				}
			},
			buy() {
				uni.navigateTo({
					url: `/pages/order/createOrder`
				})
			},
			toReviews() {
				let id = this.goodsId
				uni.navigateTo({
					url: `/pages/product/reviews?id=${id}`
				})
			},
			// 加入购物车之前的校验
			validCount() {
				// 登录校验
				if (!this.hasLogin) {
					this.$util.msg('您还未登录，请登录');
					//   setTimeout(() => {
					uni.navigateTo({
						url: '/pages/public/login'
					})
					return false
					//   }, 500)
				}
				// 库存不等原因
				if (this.isDisabled) {
					this.$util.msg('商品无法购买！')
					return false
				}
				// 参数错误
				if ((this.detailInfo.goods.moq != null) && (this.detailInfo.goods.moq > this.addnum)) {
					this.$util.msg('未达到起订量！')
					return false
				}
				// 如果库存数量小于50的情况，前端先做一次校验
				let remainAmount = this.detailInfo.protocol.remainAmount
				if (typeof remainAmount === 'number' && !isNaN(remainAmount) && this.addnum > remainAmount) {

					uni.showToast({
						title: '商品库存不足!',
						icon: 'error',
					});
															// this.$util.msg("商品库存不足！");
					return false;
				}
				return true
			},
			addCart(isMin=false) {
				console.log('this.areaId',this.areaId);
				if (!this.validCount()) {
					return
				} else {
					if(this.isbuyMinPrice&&!isMin){
						this.queryLowestPriceGoods()
						return
					}
					let pType;
					let qType;
					if (this.detailInfo.goods.goodsSourceType === 0) {
						pType = '02';
						qType = 1;
					} else {
						pType = '01';
						qType = 2;
					}
					var areaId = uni.getStorageSync('areaId') ? uni.getStorageSync('areaId') : uni.getStorageSync(
						'enterpriseInfo').areaId;
					let params = {
						num: this.addnum,
						goodsId: this.detailInfo.goods.goodsId,
						areaId: this.areaId
					};
					addToCart(params).then(res => {
						if (res.code === 0) {
							uni.showToast({
																							title: '加入购物车成功',
																							icon: 'success',
																						});
							// this.$util.msg('加入购物车成功')

						} else if(res.code === 1001) {
						let msg = ''
						if(res.extra.productAvailability) {
							msg = res.extra.productAvailability.filter(item => !item.canPurchase).map(item => item.message).toString()
						}
						this.$util.msg(res.message+' '+msg)
					}else {
							//this.$util.msg(res.message)
							if(res.message == '购物车装不下啦，请清理后再试！'){
								this.$refs.fullCartDialog.open()
							} else {
								uni.showToast({
								title:res.message,
								icon: 'error',
							});
								// this.$util.msg(res.message)
							}
						}
						this.receviverMsg(res)
					})
				}
			},
			queryLowestPriceGoods(){
				queryGoodsLowestPriceById({goodsId: this.detailInfo.goods.goodsId,purchaserId: uni.getStorageSync('deptinfo')[0].deptId}).then(response=>{
					if(response.code === 0){
					  let res = response.data;
					  if(res.goodsId) {
						  // 返回商品
						  let lowestPrice = Number(res.goodsPrice)
						  if (lowestPrice < this.detailInfo.protocol.goodsPrice){
							//不是最低价商品，需要跳转到新商品
							uni.showModal({
								title:'温馨提示',
								content:'商城存在价格更低的同类商品',
								confirmText:'前往购买',
								showCancel:false,
								success(suc) {
									if(suc.confirm){
										uni.navigateTo({
											url:`/pages/product/product?id=${res.goodsId}`
										})
									}
								}
							})
						  } else {
							this.addCart(true)
						  }
					  } else {
						this.addCart(true)
					  }
					}else{
						this.addCart(true)
					}
				})
			},
			selectAddress(address){
				console.log('接送的',address)
				this.areaId = address.areaIds||address.areaId
				this.address = address.areaName
			},
			changenum(num){
				console.log('改变数量',num)
				this.addnum=num
			},
			// 加入购物车和立即下单返回提示
			receviverMsg(res) {
				console.log('下单判断')
				// this.addnum=0
				if (res.code === 1001) {
					uni.showToast({
						title:res.message,
						icon: 'error',
					});
					// this.$util.msg(res.message)
					let remainAmount = res.data
					if (remainAmount <= 0 && this.addnum === 1) {
						this.stockStatus = '库存不足'
						this.isDisabled = true
					}
				} else if (res.code === 1002) {
					// this.$util.msg(res.message)
					uni.showToast({
						title:res.message,
						icon: 'error',
					});
					this.isDisabled = true
				}
			},
			// 关闭弹窗
			closeFullCartDialog() {
				this.$refs.fullCartDialog.close()
			},


		}
	}
</script>

<style lang='scss'>
	#html /deep/ .ssd-module-wrap {
		width: 100% !important;
		height: auto;

		.ssd-module {
			width: 100%;
			/* height: auto; */
			background-size: 100%;
			background-color: #fff;
		}
	}

	#html /deep/ img:not([usemap]) {
		width: 100%;
		height: auto !important;
	}

	#html /deep/ ul {
		list-style: none;
		padding-left: 0;
	}

	#html /deep/ img {
		width: 100%;
		height: auto !important;
	}

	page {
		background: $page-color-base;
		padding-bottom: 160upx;
	}

	.icon-you {
		font-size: $font-base + 2upx;
		color: #888;
	}

	.carousel {
		height: 100vw;
		position: relative;

		swiper {
			height: 100%;
		}

		.image-wrapper {
			width: 100%;
			height: 100%;
			position: relative;
			.soldout {
				position: absolute;
				left: 0;
				top: 0;
				right: 0;
				bottom: 0;
			}
		}

		.swiper-item {
			display: flex;
			justify-content: center;
			align-content: center;
			height: 750upx;
			overflow: hidden;

			image {
				width: 100%;
				height: 100%;
			}
		}

	}

	/* 标题简介 */
	.introduce-section {
		background: #fff;
		padding: 20upx 30upx 0 30upx;
		display: flex;
		flex-direction: column;

		.title {
			font-size: 32rpx;
			color: $font-color-dark;
			margin-bottom: 10rpx;
		}

		.goodsId {
			color: rgba(0, 0, 0, 0.65);
			font-size: 14px;
		}

		.price-box {
			display: flex;
			align-items: center;
			/* height: 64upx; */
			padding: 10upx 0;
			font-size: 26upx;
			color: $uni-color-primary;
		}

		.tit {
			width: 140upx;
		}

		.price-show {
			flex: 1;

			.price {
				font-size: $font-lg + 2upx;
			}

			.coupon-tip {
				align-items: center;
				padding: 4upx 10upx;
				background: $uni-color-primary;
				font-size: $font-sm;
				color: #fff;
				border-radius: 6upx;
				line-height: 1;
				transform: translateY(-4upx);
			}
		}

		/* .m-price {
			margin: 0 12upx;
			color: $font-color-light;
			text-decoration: line-through;
		} */




		.bot-row {
			display: flex;
			align-items: center;
			height: 50upx;
			font-size: $font-sm;
			color: $font-color-light;

			text {
				flex: 1;
			}
		}
	}

	/* 分享 */
	.share-section {
		display: flex;
		align-items: center;
		color: $font-color-base;
		background: linear-gradient(left, #fdf5f6, #fbebf6);
		padding: 12upx 30upx;

		.share-icon {
			display: flex;
			align-items: center;
			width: 70upx;
			height: 30upx;
			line-height: 1;
			border: 1px solid $uni-color-primary;
			border-radius: 4upx;
			position: relative;
			overflow: hidden;
			font-size: 22upx;
			color: $uni-color-primary;

			&:after {
				content: '';
				width: 50upx;
				height: 50upx;
				border-radius: 50%;
				left: -20upx;
				top: -12upx;
				position: absolute;
				background: $uni-color-primary;
			}
		}

		.icon-xingxing {
			position: relative;
			z-index: 1;
			font-size: 24upx;
			margin-left: 2upx;
			margin-right: 10upx;
			color: #fff;
			line-height: 1;
		}

		.tit {
			font-size: $font-base;
			margin-left: 10upx;
		}

		.icon-bangzhu1 {
			padding: 10upx;
			font-size: 30upx;
			line-height: 1;
		}

		.share-btn {
			flex: 1;
			text-align: right;
			font-size: $font-sm;
			color: $uni-color-primary;
		}

		.icon-you {
			font-size: $font-sm;
			margin-left: 4upx;
			color: $uni-color-primary;
		}
	}

	.flex {
		display: flex;
	}

	.justify-between {
		justify-content: space-between;
	}

	.drawer-list-title {
		font-size: 20rpx;
		font-weight: 400;
		line-height: 48rpx;
		/* margin: 38rpx 0 18rpx; */
		color: rgba(34, 34, 34, 1);
	}

	.drawer-list-title>text {
		font-size: 26rpx;
		color: #666666;
	}

	.draer-list-con>text {
		background: #fbecee;
		border-radius: 20px;
		color: #fb6a80;
		font-size: 28rpx;
		padding: 10rpx 28rpx;
		/* margin: 10rpx 10rpx 10rpx 0; */
		display: inline-block;
	}

	.draer-list-con>view {
		/* background: #fbecee; */
		/* border-radius: 20px; */
		color: #fb6a80;
		font-size: 28rpx;
		padding: 10rpx 28rpx;
		/* margin: 10rpx 10rpx 10rpx 0; */
		display: inline-block;
	}

	.c-list {
		font-size: $font-sm + 2upx;
		color: $font-color-base;
		background: #fff;

		.c-row {
			display: flex;
			align-items: center;
			padding: 20upx 30upx;
			position: relative;
			vertical-align: middle;
		}

		.item-list {
			flex: 1;
			display: flex;
			flex-wrap: wrap;
			align-items: center;
			text-align: center;

			text {
				background: #eee;
				margin-right: 16upx;
				margin-bottom: 20upx;
				border-radius: 100upx;
				padding: 10rpx 20upx;
				font-size: $font-base;
				min-width: 120rpx;
				color: $font-color-dark;
			}

			.selected {
				background: #fbebee;
				color: $uni-color-primary;
			}

			.isdisabled {
				background: $my-border-color;
				color: $my-text-color-grey;
			}
		}

		.uni-num-box {
			display: flex;
			margin-right: 3px;

			.add,
			.subtract {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 60rpx;
				height: 60rpx;
				color: #333;
				font-size: 38rpx;
				border: 1rpx solid #e5e5e5;
				background-color: #f8f8f8;

				&.disabled {
					color: $font-color-disabled;
				}
			}

			.count {
				display: flex;
				align-items: center;
				width: 100rpx;
				height: 60rpx;
				line-height: 50rpx;
				font-size: 14px;
				text-align: center;
				border-top: 1rpx solid #e5e5e5;
				border-bottom: 1rpx solid #e5e5e5;
				background-color: #fff;
			}
		}

		.tit {
			width: 140upx;
		}

		.con {
			//flex: 1;
			color: $font-color-dark;

			.selected-text {
				margin-right: 10upx;
			}
		}

		.m-price {
			flex: 1;
			color: $font-color-light;
			text-decoration: line-through;
		}

		.m-message {
			flex: 1;
			color: $font-color-light;
			/* text-decoration: line-through; */
		}

		.bz-list {
			height: 40upx;
			font-size: $font-sm+2upx;
			color: $font-color-dark;

			text {
				display: inline-block;
				margin-right: 30upx;
			}
		}

		.con-list {
			flex: 1;
			display: flex;
			flex-direction: column;
			color: $font-color-dark;
			line-height: 40upx;
		}

		.red {
			color: $uni-color-primary;
		}
	}

	.eva-empty {
		padding: 20upx 30upx;
		background: #fff;
		margin-top: 16upx;
		font-size: $font-base;
		color: $font-color-dark;
	}

	/* 评价 */
	.eva-section {
		display: flex;
		flex-direction: column;
		padding: 20upx 30upx;
		background: #fff;
		margin-top: 16upx;

		.e-header {
			display: flex;
			align-items: center;
			height: 70upx;
			font-size: $font-sm + 2upx;
			color: $font-color-light;

			.tit {
				font-size: $font-base + 2upx;
				color: $font-color-dark;
				margin-right: 4upx;
			}

			.tip {
				flex: 1;
				text-align: right;
			}

			.icon-you {
				margin-left: 10upx;
			}
		}
	}

	.eva-box {
		display: flex;
		padding: 20upx 0;

		.portrait {
			flex-shrink: 0;
			width: 80upx;
			height: 80upx;
			border-radius: 100px;
		}

		.right {
			flex: 1;
			display: flex;
			flex-direction: column;
			font-size: $font-base;
			color: $font-color-base;
			padding-left: 26upx;
			.imageBox{
				display: flex;
    			flex-wrap: wrap;
			}
			.con {
				padding: 20upx 0;

				text {
					font-size: $font-base;
					color: $font-color-dark;
				}
			}

			.bot {
				display: flex;
				justify-content: space-between;
				font-size: $font-sm;
				color: $font-color-light;
			}

			.time {
				text-align: right;
				font-size: $font-sm;
				color: $font-color-light;
			}
		}
	}

	/*  详情 */
	.detail-desc {
		background: #fff;
		margin-top: 16upx;

		.d-header {
			display: flex;
			justify-content: center;
			align-items: center;
			height: 80upx;
			font-size: $font-base + 2upx;
			color: $font-color-dark;
			position: relative;

			text {
				padding: 0 20upx;
				background: #fff;
				position: relative;
				z-index: 1;
			}

			&:after {
				position: absolute;
				left: 50%;
				top: 50%;
				transform: translateX(-50%);
				width: 300upx;
				height: 0;
				content: '';
				border-bottom: 1px solid #ccc;
			}
		}

		.desc {
			width: 100%;
			text-align: center;
			padding-bottom: 20rpx;

			image {
				background-color: #fff;
			}

			.name {
				display: block;
				margin-bottom: 20rpx;
				text-align: center;
				width: 100%;
				padding: 0 20rpx;
				font-size: $font-base + 2upx;
				background: #fff;
				word-break: break-all;
			}

			.html {
				box-sizing: border-box;
				height: auto;

				/deep/ img:not([usemap]) {
					width: 100%;
					height: auto !important;
				}

				/deep/ ul {
					list-style: none;
					padding-left: 0;
				}

				view {
					height: auto;
				}
			}
		}
	}

	/* 规格选择弹窗 */
	.attr-content {
		padding: 10upx 30upx;

		.a-t {
			display: flex;

			image {
				width: 170upx;
				height: 170upx;
				flex-shrink: 0;
				margin-top: -40upx;
				border-radius: 8upx;
				;
			}

			.right {
				display: flex;
				flex-direction: column;
				padding-left: 24upx;
				font-size: $font-sm + 2upx;
				color: $font-color-base;
				line-height: 42upx;

				.price {
					font-size: $font-lg;
					color: $uni-color-primary;
					margin-bottom: 10upx;
				}

				.selected-text {
					margin-right: 10upx;
				}
			}
		}

		.attr-list {
			display: flex;
			flex-direction: column;
			font-size: $font-base + 2upx;
			color: $font-color-base;
			padding-top: 30upx;
			padding-left: 10upx;
		}

		.item-list {
			padding: 20upx 0 0;
			display: flex;
			flex-wrap: wrap;

			text {
				display: flex;
				align-items: center;
				justify-content: center;
				background: #eee;
				margin-right: 20upx;
				margin-bottom: 20upx;
				border-radius: 100upx;
				min-width: 60upx;
				height: 60upx;
				padding: 0 20upx;
				font-size: $font-base;
				color: $font-color-dark;
			}

			.selected {
				background: #fbebee;
				color: $uni-color-primary;
			}

			.isdisabled {
				background: $my-border-color;
				color: $my-text-color-grey;
			}
		}
	}

	/*  弹出层 */
	.popup {
		position: fixed;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
		z-index: 9999;

		&.show {
			display: block;

			.mask {
				animation: showPopup 0.2s linear both;
			}

			.layer {
				animation: showLayer 0.2s linear both;
			}
		}

		&.hide {
			.mask {
				animation: hidePopup 0.2s linear both;
			}

			.layer {
				animation: hideLayer 0.2s linear both;
			}
		}

		&.none {
			display: none;
		}

		.mask {
			position: fixed;
			top: 0;
			width: 100%;
			height: 100%;
			z-index: 1;
			background-color: rgba(0, 0, 0, 0.4);
		}

		.layer {
			position: fixed;
			z-index: 99;
			bottom: 0;
			width: 100%;
			min-height: 40vh;
			border-radius: 10upx 10upx 0 0;
			background-color: #fff;

			.btn {
				height: 66upx;
				line-height: 66upx;
				border-radius: 100upx;
				background: $uni-color-primary;
				font-size: $font-base + 2upx;
				color: #fff;
				margin: 30upx auto 20upx;
			}
		}

		@keyframes showPopup {
			0% {
				opacity: 0;
			}

			100% {
				opacity: 1;
			}
		}

		@keyframes hidePopup {
			0% {
				opacity: 1;
			}

			100% {
				opacity: 0;
			}
		}

		@keyframes showLayer {
			0% {
				transform: translateY(120%);
			}

			100% {
				transform: translateY(0%);
			}
		}

		@keyframes hideLayer {
			0% {
				transform: translateY(0);
			}

			100% {
				transform: translateY(120%);
			}
		}
	}

	/* 底部操作菜单 */
	.page-bottom {
		position: fixed;
		left: 5%;
		bottom: 30upx;
		z-index: 95;
		display: flex;
		justify-content: center;
		align-items: center;
		width: 90%;
		height: 100upx;
		background: rgba(255, 255, 255, .9);
		box-shadow: 0 0 20upx 0 rgba(0, 0, 0, .5);
		border-radius: 16upx;
		padding-left: 10rpx;
		padding-right: 20rpx;

		.p-b-btn {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			font-size: $font-sm;
			color: $font-color-base;
			width: 96upx;
			height: 80upx;

			.yticon {
				font-size: 40upx;
				line-height: 48upx;
				color: $font-color-light;
			}

			&.active,
			&.active .yticon {
				color: $uni-color-primary;
			}

			.icon-fenxiang2 {
				font-size: 42upx;
				transform: translateY(-2upx);
			}

			.icon-shoucang {
				font-size: 46upx;
			}
		}
.btn-area-now {
			height: 76upx;
			border-radius: 100px;
			display: flex;
			align-items: center;
			justify-content: center;
			overflow: hidden;
			box-shadow: 0 20upx 40upx -16upx #fa436a;
			box-shadow: 1px 2px 5px rgba(219, 63, 96, 0.4);
			background: linear-gradient(to right, #ffac30, #fa436a, #F56C6C);
			margin-right: 0;
			position: relative;
			width: 110px;
			margin-left: 10rpx;
			font-size: $font-base;

		}
		.btn-area {
			height: 76upx;
			border-radius: 100px;
			overflow: hidden;
			box-shadow: 0 20upx 40upx -16upx #fa436a;
			box-shadow: 1px 2px 5px rgba(219, 63, 96, 0.4);
			margin-right: 0;
			position: relative;
			width: 130px;
			font-size: $font-base;

			&.disabled {
				background-color: #c6c6c6 !important;
			}

			&.able {
				background: linear-gradient(to right, #ffac30, #fa436a, #F56C6C);
			}
		}

		.action-btn-group {
			display: flex;
			height: 76upx;
			border-radius: 100px;
			overflow: hidden;
			box-shadow: 0 20upx 40upx -16upx #fa436a;
			box-shadow: 1px 2px 5px rgba(219, 63, 96, 0.4);
			background: linear-gradient(to right, #ffac30, #fa436a, #F56C6C);
			margin-left: 20upx;
			position: relative;

			&:after {
				content: '';
				position: absolute;
				top: 50%;
				right: 50%;
				transform: translateY(-50%);
				height: 28upx;
				width: 0;
				border-right: 1px solid rgba(255, 255, 255, .5);
			}

			.action-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 180upx;
				height: 100%;
				font-size: $font-base;
				padding: 0;
				border-radius: 0;
				background: transparent;
			}
		}
	}

	.popupBg {
		background: #f8f8f8;
		position: absolute;
		padding: 20rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		box-sizing: border-box;
	}
	.uni-tip {
		overflow: hidden;

		.popup-content {

			.cancel-reason {
				width: 100%;
				height: 102rpx;
				line-height: 100%;
				padding: 16rpx;
				color: #303133;
				font-size: $my-font-size-base;
				border: 1px solid #f5f5f5;
				border-radius: 10rpx;
			}
		}

		.uni-tip-group-button {
			border-top: none;

			.uni-tip-button {
				border-top: 1px solid #e2e2e2;
				display: flex;
				align-items: center;
				line-height: normal;
				justify-content: center;

				&.confirm {
					border-top: 1rpx solid $base-color;
					border-bottom: 1rpx solid $base-color;
					color: #fff;
					background-color: $base-color;
				}
			}
		}
	}
	.cart-icon,
		.top-back {
			width: 85rpx;
			height: 85rpx;
			position: fixed;
			right: 34rpx;
			bottom: 200rpx!important;
			-webkit-overflow-scroll: touch;
			z-index: 100000;
		}
</style>
